
let {mat4} = require('gl-matrix');


let tmpMvMat = mat4.create();

class SimpleGameItem {

    /**
     *
     * @param data =  {
        positions: posArray,
        normals: normalArray,
        texCoords: texCoordArray,
        indices: indicesArray,
    };
     * @param options
     */
    constructor(shaderInfo,data) {
        let gl = globalThis.app.gl;
        this.shaderInfo = shaderInfo;

        // vao
        let vao = this.vao = gl.createVertexArrayOES();
        gl.bindVertexArrayOES(vao);

        // posVAO
        let posVAO = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, posVAO);
        gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(data.positions),gl.STATIC_DRAW);
        gl.enableVertexAttribArray(shaderInfo.attribs['a_position']);
        gl.vertexAttribPointer(shaderInfo.attribs['a_position'],3,gl.FLOAT,false,0,0);

        let indiceVBO = gl.createBuffer();
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,indiceVBO);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,new Uint16Array(data.indices),gl.STATIC_DRAW);
        this.drawVertexCount = data.indices.length;
        gl.bindVertexArrayOES(null);

        //-----------------------------------
        // 包含基本的 T R S
        this.transMat = mat4.create();
        this.rotateMat = mat4.create();
        this.scaleMat = mat4.create();

        this.worldMatrix = mat4.create();
    }

    render(camera){
        let gl = globalThis.app.gl;
        let shaderInfo = this.shaderInfo;
        gl.useProgram(shaderInfo.program);

        gl.uniformMatrix4fv(shaderInfo.uniforms['projMatrix'],false,camera.projMatrix);

        mat4.mul(this.worldMatrix,this.transMat,this.rotateMat);
        mat4.mul(this.worldMatrix,this.worldMatrix,this.scaleMat);
        mat4.mul(tmpMvMat,camera.viewMatrix,this.worldMatrix);

        gl.uniformMatrix4fv(shaderInfo.uniforms['mvMatrix'],false,tmpMvMat);

        gl.uniform1f(shaderInfo.uniforms['near'],camera.near);
        gl.uniform1f(shaderInfo.uniforms['far'],camera.far);

        gl.bindVertexArrayOES(this.vao);
        gl.drawElements(gl.TRIANGLES,this.drawVertexCount,gl.UNSIGNED_SHORT,0);

        gl.bindVertexArrayOES(null);
        gl.useProgram(null);
    }
}

module.exports = SimpleGameItem;
